/*
 *  Copyright 2012 Dirk Vranckaert
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package eu.vranckaert.vvl.utils.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import eu.vranckaert.vvl.R;

import java.util.List;

/**
 * User: DIRK VRANCKAERT
 * Date: 16/02/12
 * Time: 21:27
 */
public class MultiSelectSpinner extends Spinner implements DialogInterface.OnMultiChoiceClickListener {

    private List<String> items;
    private boolean[] selected;
    private boolean[] tmpSelected;
    private String allSelectedText;
    private String noneSelectedText;
    private MultiSelectSpinnerListener listener;
    private String title;

    public MultiSelectSpinner(Context context) {
        super(context);
    }

    public MultiSelectSpinner(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
    }

    public MultiSelectSpinner(Context arg0, AttributeSet arg1, int arg2) {
        super(arg0, arg1, arg2);
    }

    @Override
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        if (isChecked)
            tmpSelected[which] = true;
        else
            tmpSelected[which] = false;
    }

    public void positiveAction(DialogInterface dialog) {
        selected = tmpSelected;
        // refresh text on spinner
        StringBuffer spinnerBuffer = new StringBuffer();
        boolean someUnselected = false;
        boolean allUnselected = true;
        for (int i = 0; i < items.size(); i++) {
            if (selected[i] == true) {
                allUnselected = false;
                spinnerBuffer.append(items.get(i));
                spinnerBuffer.append(", ");
            } else {
                someUnselected = true;
            }
        }
        String spinnerText;
        
        if (allUnselected) {
            spinnerText = this.noneSelectedText;
        } else {
            if (someUnselected) {
                spinnerText = spinnerBuffer.toString();
                if (spinnerText.length() > 2)
                    spinnerText = spinnerText.substring(0, spinnerText.length() - 2);
            } else {
                spinnerText = allSelectedText;
            }
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_item,
                new String[] { spinnerText });
        setAdapter(adapter);
        listener.onItemsSelected(selected);
    }

    private void cancelAction(DialogInterface dialog) {
        tmpSelected = null;
    }

    @Override
    public boolean performClick() {
        tmpSelected = new boolean[selected.length];
        for (int i=0; i<selected.length; i++) {
            tmpSelected[i] = new Boolean(selected[i]);
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(title);
        builder.setMultiChoiceItems(
                items.toArray(new CharSequence[items.size()]), tmpSelected, this);
        builder.setPositiveButton(R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        positiveAction(dialog);
                    }
                });
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cancelAction(dialog);
            }
        });
        builder.show();
        return true;
    }

    public void setItems(List<String> items, List<Boolean> checked, String allSelectedText, String noneSelectedText, String title, MultiSelectSpinnerListener listener) {
        this.items = items;
        this.allSelectedText = allSelectedText;
        this.noneSelectedText = noneSelectedText;
        this.title = title;
        this.listener = listener;

        selected = new boolean[items.size()];
        int numberOfSelected = 0;
        String spinnerText = "";
        for (int i = 0; i < selected.length; i++) {
            selected[i] = checked.get(i);
            if (checked.get(i)) {
                numberOfSelected++;
                spinnerText += items.get(i) + ", ";
            }
        }
        if (spinnerText.length() > 0) {
            spinnerText = spinnerText.substring(0, spinnerText.length()-2);
        }
        
        if (numberOfSelected == items.size()) {
            spinnerText = allSelectedText;
        } else if (numberOfSelected == 0) {
            spinnerText = noneSelectedText;
        }

        // all text on the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_item, new String[] { spinnerText });
        setAdapter(adapter);
    }

    public interface MultiSelectSpinnerListener {
        public void onItemsSelected(boolean[] selected);
    }
}
